package tgc.tdu.tgq.demo.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.tdu.tgq.demo.entity.TbClass;
import tgc.tdu.tgq.demo.service.TbClassService;
import tgc.tdu.tgq.demo.web.form.ClassForm;


@Controller
@RequestMapping(value = "/classmanage")
public class Classmanage {
	@Autowired
	private TbClassService classService;
	
	@RequestMapping(value = "/manage")
	public void manage() {	
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(ClassForm form) {
		Specification<TbClass> spec=buildSpec(form);
		return classService.findAll(spec);
	}
	
	@RequestMapping(value = "/edit")
	public void edit(Integer id,ModelMap modelMap) {
		TbClass model=new TbClass();
		if(id!=null) {
			model=classService.findById(id);
		}
		modelMap.put("model", model);
	}
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(ClassForm form) {
		TbClass model=new TbClass();
		Integer id=form.getId();
		if(id!=null) {
			model=classService.findById(id);
		}
		BeanUtils.copyProperties(form, model,"id");
		classService.save(model);
		return "OK";
	}
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(Integer id) {
		classService.deleteById(id);
		return "OK";
	}
	@RequestMapping(value = "/search",method = RequestMethod.GET)
	/* ModelMap传递控制方法传递数据到结果页面。类似于request的setAttribute方法的作用。 */
	public void search(ClassForm form,ModelMap modelMap) {
		modelMap.put("model", form);
	}
	
	private Specification<TbClass> buildSpec(ClassForm form) {
		Specification<TbClass> spec=new Specification<TbClass>() {

			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String manager = form.getManager();
				if(StringUtils.hasText(manager)) {
					rules.add(cb.like(root.get("manager"), "%"+manager+"%"));
				}
				String name=form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	
}
